
import { ref } from "vue";
import { useCool, useStore } from "/@/cool";
import { useUi } from "/$/cool-ui";
import { adMpWxPlayMusic, adPlayMusic,adMusicValueArr } from "./audio";
// const ui = useUi();
export const rewardedLoading = ref(false)
export const rewardedFunction = ref("")
export const rewardedFunctionItem=ref()
// 广告加载事件
export function rewardedLoad() {
	rewardedLoading.value = false;
	console.log('广告数据加载成功');
}
// 广告加载失败事件
export function rewardedError(e : any) {
	// 广告加载失败
	console.log("onaderror: ", e.detail);
	if(e.detail?.errMsg){
		setAdInfo(2, e.detail.errMsg)
	}
	rewardedLoading.value = false;
}
// 广告关闭事件
export function rewardedClose(e : any) {
	const detail = e.detail
	// 用户点击了【关闭广告】按钮
	if (detail && detail.isEnded) {
		// 正常播放结束
		console.log("onadclose " + detail.isEnded);
		setAdInfo(1, detail.isEnded)
		
	} else {
		// 播放中途退出
		console.log("onadclose " + detail.isEnded);
		setAdInfo(0, detail.isEnded)
	}
}
// 是否展示广告 用户可观看广告次数>0且非特殊用户,随机数为2就展示广告
export function isAdvertising() {
	let info = useStore().user?.info
	return new Promise(async (resolve) => {
		if (info) {
			// 广告可观看次数大于0 adViewing为0 需要看广告
			if (info?.adNumber > 0 && info?.adViewing == 0) {
				// if (getRandomInteger(1, 2) == 2) {
					useUi().showConfirm({
						title: "广告",
						message: `需要播放一段广告用于助念器的日常维护,播放${info?.adNumber}次后当日不再弹框`,
						showCancelButton: true,
						confirmButtonText: "播放",
						cancelButtonText: "取消",
						callback(action) {
							if (action == "confirm") {
								useUi().showAdRewared()
								resolve(2)
							} else {
								// useUi().showToast("已取消播放")
								resolve(0)
							}
						}
					});
				// } else {
				// 	resolve(1)
				// }
			} else {
				resolve(1)
			}
		} else {
			resolve(1)
		}
	})

}
function executionFunction(){
	if(rewardedFunction.value=='adMusicValueArr'){
		adMusicValueArr(rewardedFunctionItem.value)
	}else if(rewardedFunction.value=='adPlayMusic'){
		adPlayMusic()
	}else if(rewardedFunction.value=='adMpWxPlayMusic'){
		adMpWxPlayMusic()
	}
	rewardedFunction.value=""
}
// 生成随机数
function getRandomInteger(min : number, max : number) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}
function setAdInfo(status : any, remark = '') {
	if(status!=0){
		executionFunction()
	}
	if (useStore().user.token) {
		useCool().service.user.adInfo.add({ status, remark }).then(res => {
			useStore().user.get();
		})
	}
}